const app = getApp();
let timer;
Page({

  data: {
    logo:'',
    loginType: 1, //1账号密码登录 2手机号码和验证码 3微信登录
    smsText: "获取验证码",
    smsDisabled: false,
    account: "", //账号
    password: '', //密码
    phone: '', //手机号码
    code: '', // 验证码
    msg: "请使用手机登录或者微信授权登录，登录账号后进入设置界面修改账号密码。",
    show: false,
  },

  onLoad: function () {
    this.getOpenId();
    this.getCompanyImg();
  },

  onUnload: function () {
    clearTimeout(timer);
  },
  // 获取logo
  getCompanyImg: function () {
    var that = this;
    var company_no = app.globalData.company_no
    // ajax请求
    app.ajax({
      url: 'Api/Company/getCompayConfig',
      url_type: 1,
      data: { company_no },
      success: function (res) {
        if (res.data.code == 1) {
          that.setData({
            logo: res.data.data.img_config.image
          })
        }
      }
    })
  },

  forgetPassword() {
    clearTimeout(timer);
    this.setData({
      show: true
    }, () => {
      timer = setTimeout(() => {
        this.setData({
          show: false
        }, () => {
          clearTimeout(timer)
        })
      }, 4000)
    })
  },

  getOpenId() {
    wx.login({
      success: results => {
        app.ajax({
          url: "Common/Wx/getUserOpenid",
          data: {
            code: results.code
          },
          success: res => {
            if (res.data.code == 1000) {
              wx.setStorageSync('openid', res.data.data.openid);
              wx.setStorageSync('session_key', res.data.data.session_key);
            }
          }
        })
      },
      fail: e => {
        app.showToast("微信登录失败")
      }
    })
  },





  submit(e) {
    console.log(e.detail.value);
    const formData = e.detail.value;
    const loginType = this.data.loginType;
    let data = {};
    if (loginType == 1) {
      if (formData.account == "") {
        app.showToast("请输入账号");
        return false;
      }
      if (formData.password == "") {
        app.showToast("请输入密码");
        return false;
      }
      Object.assign(data, {
        account: formData.account,
        password: formData.password,
        type: 0,
      })
    }
    if (loginType == 2) {
      if (formData.phone == "") {
        app.showToast("请输入手机号码");
        return false;
      }
      if (formData.code == "") {
        app.showToast("请输入验证码");
        return false;
      }
      Object.assign(data, {
        phone: formData.phone,
        code: formData.code,
        type: 2
      })
    }
    this.excuteLogin(data);
  },

  getPhoneNumber(e) {
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      this.excuteLogin({
        data: e.detail.encryptedData,
        iv: e.detail.iv,
        key: wx.getStorageSync("session_key"),
        type: 1
      });
    }
  },

  handleInputPhone(e) {
    this.setData({
      phone: e.detail.value
    })
  },

  //登录ajax
  excuteLogin(data) {
    wx.showLoading({
      mask: true,
    })
    app.ajax({
      url: "Partner/User/login",
      data,
      success: res => {
        wx.hideLoading();
        if (res.data.code == 200) {
          //多个角色需要跳转到role界面处理
          let source = res.data.data;
          if (source.length > 1) {
            wx.navigateTo({
              url: 'role',
              success: res => {
                res.eventChannel.emit("acceptDataFromOpenerPage", source);
              }
            })
          } else {
            wx.setStorageSync('token', source[0].token)
            app.ajax({
              url: "Partner/User/InfoUpdate",
              data: {
                openid: wx.getStorageSync('openid')
              },
              success: res => {
                if (res.data.code == 200) {
                  app.showToast("登录成功", "success");
                  let role = source[0].role;
                  wx.setStorageSync('role', role);
                  //服务器端返回的角色定义数值 1维修人员  2销售 3合伙人
                  if (role == 1) {
                    this.getEngineerInfo();
                    setTimeout(() => {
                      wx.reLaunch({
                        url: '../../engineering/pages/index/index',
                      })
                    }, 1000)
                  } else if (role == 2) {
                    this.getSalemanInfo();
                    setTimeout(() => {
                      wx.reLaunch({
                        url: '../../promoter/pages/index/index',
                      })
                    }, 1000)
                  } else {
                    this.getPartnerInfo();
                    setTimeout(() => {
                      wx.switchTab({
                        url: '../partner/index/index',
                      })
                    }, 1000)
                  }
                } else {
                  app.showToast(res.data.message)
                }
              },
              error: e => {
                app.showToast("网络错误");
              }
            })
          }
        } else {
          app.showToast(res.data.message)
        }
      },
      error: e => {
        wx.hideLoading();
        app.showToast("网络错误");
      }
    })
  },





  setLoginHistoryRoles(userInfo) {
    const loginHistoryRoles = wx.getStorageSync('loginHistoryRoles') || [];
    let role = wx.getStorageSync('role');
    userInfo.role = role //将Storage的角色打放入userInfo
    if (loginHistoryRoles.length == 0) {
      loginHistoryRoles.push(userInfo);
    } else {
      let max = 5; //最多5条历史登录数据
      let index = loginHistoryRoles.findIndex(item => {
        return item.role == role && item.id == userInfo.id
      });
      if (~index) {
        loginHistoryRoles[index] = userInfo;
      } else {
        if (loginHistoryRoles.length < max) {
          loginHistoryRoles.unshift(userInfo);
        } else {
          loginHistoryRoles.pop();
          loginHistoryRoles.unshift(userInfo);
        }
      }
    }
    wx.setStorageSync('loginHistoryRoles', loginHistoryRoles)
  },



  getPartnerInfo() {
    app.ajax({
      url: "Partner/User/getPartnerInfo",
      success: res => {
        if (res.data.code == 200) {
          let origin = res.data.data;
          let userInfo = {
            id: origin.id,
            name: origin.account_name,
            account: origin.account,
            token: wx.getStorageSync('token')
          };
          this.setLoginHistoryRoles(userInfo);
        }
      }
    })
  },


  //获取销售的相关信息
  getSalemanInfo() {
    app.ajax({
      url: 'Salesman/Login/getInfo',
      data: {},
      success: res => {
        if (res.data.code == 1000) {
          wx.setStorageSync('userInfo', res.data.data);
          wx.setStorageSync('salesman_id', res.data.data.id);
          let origin = res.data.data;
          let userInfo = {
            id: origin.id,
            name: origin.full_name,
            account: origin.account,
            token: wx.getStorageSync('token')
          };
          this.setLoginHistoryRoles(userInfo);
        }
      }
    })
  },

  //获取维修员信息
  getEngineerInfo() {
    app.ajax({
      url: 'Manage/User/getManageInfo',
      method: "POST",
      data: {},
      success: res => {
        if (res.data.code == 200) {
          wx.setStorageSync('userInfo', res.data.data);
          let origin = res.data.data;
          let userInfo = {
            id: origin.id,
            name: origin.name,
            account: origin.account,
            token: wx.getStorageSync('token')
          };
          this.setLoginHistoryRoles(userInfo);
        }
      }
    })
  },




  //切换登录方式
  switchLoginType(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      loginType: type
    })
  },

  //获取短信验证码
  getSMSCode() {
    if (this.data.phone == "") {
      app.showToast("请输入手机号码");
      return false;
    }
    if (this.data.smsDisabled) {
      return;
    }
    app.ajax({
      url: "Common/Common/sendSms",
      data: {
        phone: this.data.phone
      },
      success: res => {
        if (res.data.code > 0) {
          app.showToast(res.data.message, "none", 3000);
          this.setData({
            smsDisabled: true,
          })
          this.doLoop(60);
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        app.showToast("网络错误");
      }
    });
  },

  doLoop(seconds) {
    seconds = seconds ? seconds : 60;
    this.setData({
      smsText: seconds + "s后获取",
    });
    let countdown = setInterval(() => {
      if (seconds > 0) {
        this.setData({
          smsText: seconds + "s后获取"
        });
        --seconds;
      } else {
        this.setData({
          smsText: "获取验证码",
          smsDisabled: false,
        });
        clearInterval(countdown);
      }
    }, 1000);
  },
  //申请成为合伙人
  partnerApply(){
    wx.navigateTo({
      url: '../partner/partnerApply/partnerApply',
    })
  }
})